package renpyas3.model.structs
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import org.osflash.thunderbolt.Logger;
	import renpyas3.model.AssetsLoader;
	
	/**
	 * One of the images. We don't handle different states for the image, 
	 * we treat every state (like smile, surprised) as a separate RenpyImage
	 */
	public class RenpyImage
	{
		private var _name:String;
		private var _filename:String;
		private var _loader:Loader;
		private var _path:String;
		private var _isAnimation:Boolean;
		private var _vectorOfLines:Vector.<String>;
		private var _animFramesFileNames:Vector.<String>;
		private var _animFramesDurations:Vector.<Number>;
		private var _assetsLoaderPtr:AssetsLoader;
		private var _pathAndFilename:String;
		
		public function RenpyImage(vectorOfLines:Vector.<String>, line:String,lineNumber:uint,path:String,assetsLoaderPtr:AssetsLoader)  
		{
			_vectorOfLines = vectorOfLines;
			_path = path;
			_assetsLoaderPtr = assetsLoaderPtr;

			_isAnimation = false;
			parseImage(line, lineNumber);
			
			if (_isAnimation)
			{
				loadAnimFiles();
			}
			else
			{
				loadFilename();
			}
		}

		/**
		 * load only all the frames of an animation
		 */
		private function loadAnimFiles():void
		{
			for (var i:uint = 0; i < _animFramesFileNames.length ; i++)
			{
				_assetsLoaderPtr.add(_animFramesFileNames[i]);
				/*
				var animFrameLoader:Loader = new Loader();		
				animFrameLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoadImageComplete, false, 0, true);
				animFrameLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleLoadImageIOerror,false,0,true);
				animFrameLoader.load(new URLRequest(_path + _animFramesFileNames[i]));
				_animFrames.push(animFrameLoader);
				*/
			}
			
		}

		/**
		 * load only one filename
		 */
		private function loadFilename():void
		{
			/*
			_loader = new Loader();
			
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoadImageComplete, false, 0, true);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleLoadImageIOerror,false,0,true);
			_loader.load(new URLRequest(_path+_filename));
			*/
			_pathAndFilename = _path + _filename;
			_assetsLoaderPtr.add(_pathAndFilename);
		}
		
        private function handleLoadImageComplete(e:Event):void 
		{
            //Logger.info("RenpyImage::handleLoadImageComplete: " + e);
        }

		
		private function parseImage(line:String, lineNumber:uint):void
		{
			line = f_trim(line);
			var secondWordIndex:int = line.indexOf(" ");
			var equalsSignIndex:int = line.indexOf("=");
			if (secondWordIndex == -1)
			{
				Logger.error("RenpyImage::parseImage ERROR trying to find image name in:"+ line+ " -lineNumber:"+lineNumber);
			}
			else if (equalsSignIndex == -1)
			{
				Logger.error("RenpyImage::parseImage ERROR trying to find = after label name in:"+ line+ " -lineNumber:"+lineNumber);
			}
			else
			{
				_name = line.substr(secondWordIndex + 1, equalsSignIndex - secondWordIndex - 1);
				_name = f_trim(_name);
				
				_filename = line.substr(equalsSignIndex +1);
				if (_filename.indexOf("Animation") != -1 && _filename.indexOf("(") != -1)
				{
					//is animation
					_isAnimation = true;
					readAnimDescription(lineNumber, _filename.substring(_filename.indexOf("(")+1));
				}
				else
				{
					//is single image
					_isAnimation = false;
					_filename = _filename.replace("\"", ""); //remove question marks
					_filename = _filename.replace("\"", ""); //remove last question marks
					_filename = f_trim(_filename);
					
					Logger.info("RenpyImage::parseImage:" + _name + ",  _filename:"+_filename+"<"); 
				}
			}
		}
		
		/**
		 * read all the file names of an animated sequence 
		 */
		private function readAnimDescription(lineNumber:uint, firstLine:String ):void
		{
			_animFramesFileNames = new Vector.<String>();
			_animFramesDurations = new Vector.<Number>();
	
			var currLine:String = firstLine;
			var currLineNumber:Number = lineNumber;
			parseAnimDescriptionLine(currLine, currLineNumber);
			do
			{
				currLineNumber++;
				currLine = _vectorOfLines[currLineNumber];
				parseAnimDescriptionLine(currLine, currLineNumber);
			}
			while(currLine.indexOf(")") == -1)
		}
		

		/**
		 * extract one filename and push it to the list
		 */
		private function parseAnimDescriptionLine(line:String,lineNumber:uint):void
		{
			line = f_trim(line);
			var firstColonIndex:int = line.indexOf(",");
			var secondColonIndex:int = line.indexOf(",",firstColonIndex+1);
			if (firstColonIndex == -1)
			{
				Logger.error("RenpyImage::parseAnimDescriptionLine ERROR trying to find firstColonIndex after label name in:"+line+" -lineNumber:"+lineNumber);
			}
			else
			{
				var thisFileName:String = line.substr(0, firstColonIndex-1);
				thisFileName = thisFileName.replace("\"", ""); //remove question marks
				thisFileName = thisFileName.replace("\"", ""); //remove last question marks
				thisFileName = f_trim(thisFileName);
				
				var duration:String = line.substr(firstColonIndex +1);
				duration = duration.replace(",", ""); //remove colon
				duration = duration.replace(")", ""); //remove parenthesis
				duration = f_trim(duration);
				
				_animFramesFileNames.push(_path+thisFileName);
				_animFramesDurations.push(Number(duration));
				Logger.info("RenpyImage::parseAnimDescriptionLine" + _name + ",  _thisFileName:"+thisFileName+",  duration:"+duration); 
			}
		}

		/**
		 * remove whitespace at the begginning and end
		 */
		public static function f_trim(str:String):String
		{
			//remove whitespace
			return(str.replace(/^\s+|\s+$/g, ""));
		}

		public function get name():String { return _name; }
		
		public function get loader():Loader { return _loader; }
		
		public function get isAnimation():Boolean { return _isAnimation; }
		
		public function get animFramesDurations():Vector.<Number> { return _animFramesDurations; }
		
		public function get animFramesFileNames():Vector.<String> { return _animFramesFileNames; }
		
		public function get pathAndFilename():String { return _pathAndFilename; }
	}
}